<template>
  <v-container>
    <v-card>
      <v-card-title>
        系统日志

        <v-spacer></v-spacer>

        <!-- 倒序开关 -->
        <v-switch
          v-model="reverseOrder"
          label="倒序显示"
          inset
          color="primary"
          hide-details
        ></v-switch>

        <!-- 导出按钮 -->
        <v-btn icon @click="exportLogs" title="导出日志">
          <v-icon>mdi-download</v-icon>
        </v-btn>
      </v-card-title>

      <v-card-text>
        <v-data-table-virtual
          :items="orderedLogs"
          :headers="headers"
          :height="450"
          :item-height="32"
        >
          <template #item.index="{ index }">
            {{ index + 1 }}
          </template>

          <template #item.log="{ item }">
            <pre style="white-space: pre-wrap; margin: 0">{{ item.log }}</pre>
          </template>
        </v-data-table-virtual>
      </v-card-text>
    </v-card>
  </v-container>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useLogSocketStore } from '@/stores/LogSocketStore.js'

const store = useLogSocketStore()
const reverseOrder = ref(true)

// 表头
const headers = [
  { text: '序号', value: 'index', width: '70px' },
  { text: '日志内容', value: 'log' },
]

// 排序后的日志
const orderedLogs = computed(() =>
  reverseOrder.value ? [...store.logs].slice().reverse() : store.logs,
)

// 导出
const exportLogs = () => {
  const content = store.logs.map((item) => item.log).join('\n')
  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = 'system-logs.txt'
  link.click()
  URL.revokeObjectURL(link.href)
}

onMounted(() => {
  store.connect()
})
</script>
